package com.web.task;

import com.web.config.BaseReqConfig;
import com.web.config.KftPayCommConfig;
import com.web.config.KppAppPayConfiguration;
import com.web.dao.*;
import com.web.dto.StoreApplyDto;
import com.web.entity.*;
import com.web.kftsdk.api.KftPayConfigStorage;
import com.web.kftsdk.api.KftPayService;
import com.web.kftsdk.bean.BankEnum;
import com.web.kftsdk.bean.MerchantTypeEnum;
import com.web.kftsdk.common.bean.PayRes;
import com.web.kftsdk.entity.*;
import com.web.manager.jpush.SendJPushMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author FDjavaone
 * @date 2018/7/13
 */
@Component
@Configurable
@EnableScheduling
@Slf4j
public class OldStoreKftSignUpJob {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private KftApplyMapper kftApplyMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private BankMapper bankMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private KftPayCommConfig kftPayCommConfig;
    @Autowired
    private KppAppPayConfiguration kppAppPayConfiguration;
    @Autowired
    private BaseReqConfig baseReqConfig;
    @Autowired
    private KftprovincialcityMapper kftprovincialcityMapper;
    @Autowired
    private KftBusinesscategoryMapper kftBusinesscategoryMapper;

    @Scheduled(cron = "0 */1 * * * ?")
    public void signUp() throws Exception {
        //老用户 待注册 快付通商户的记录  单次任务处理最多100条
        //即查询所有注册快付通二级商户待提交的商家
        List<StoreApplyDto> storeApplyDtos = storeMapper.selectAllKftNeed();
        log.info( "需要发起第三方支付注册数：" + storeApplyDtos.size() );

        KftPayConfigStorage kftPayConfigStorage = new KftPayConfigStorage();
        kftPayConfigStorage.setPackPath( kftPayCommConfig.getPackPath() );
        kftPayConfigStorage.setSftpPath( kftPayCommConfig.getSftpPath() );
        kftPayConfigStorage.setSftpHost( kftPayCommConfig.getSftpHost() );
        kftPayConfigStorage.setSftpUsername( kftPayCommConfig.getSftpUsername() );
        kftPayConfigStorage.setSftpPassword( kftPayCommConfig.getSftpPassword() );
        kftPayConfigStorage.setKeyPrivate( kftPayCommConfig.getKeyPrivate() );
        kftPayConfigStorage.setDevGateWay( kftPayCommConfig.getDevGateWay() );
        kftPayConfigStorage.setGateWay( kftPayCommConfig.getGateWay() );
        kftPayConfigStorage.init();
        KftPayService kftPayService = new KftPayService( kftPayConfigStorage );
        for (StoreApplyDto storeApplyDto : storeApplyDtos) {
            log.info( "店铺：" + storeApplyDto.getMerchantName() + "。开始注册流程！" );
            //一个商家可以绑定多张银行卡
            List<Bank> banks = bankMapper.selectByMid( storeApplyDto.getMId() );
            log.info( "银行卡绑定数：" + banks.size() );
            KftApply kftApply = kftApplyMapper.findByMid( storeApplyDto.getMId() );
            Date date = new Date();
            if (banks.size() == 0) {
                Message message = new Message();
                message.setFrom( 0L );
                message.setTarget( storeApplyDto.getMId() );
                message.setCreateTime( date );
                message.setModifyTime( date );
                message.setContent( "您未绑定任何银行卡,请补全信息后再通过秒升app进行第三方支付！" );
                messageMapper.insertSelective( message );
                SendJPushMessage.jPushByMessage( message );
                //注册快付通二级商户失败
                kftApply.setStatus( 3 );
                kftApply.setReason( "账户下未绑定任何银行卡!" );
                kftApplyMapper.updateByPrimaryKeySelective( kftApply );
                continue;
            }

            //取其中第一张银行卡进行注册
            String bankNo = getBankId( banks.get( 0 ).getBankName() );
            if (bankNo == null || "".equals( bankNo )) {
                log.info( "第一张银行卡归属银行不支持注册，卡号：" + banks.get( 0 ).getCardNo() );
                continue;
            }

            IdentificationReq identificationReq = new IdentificationReq();

            PayRes payRes = null;
            if (storeApplyDto.getStoreType().equals( 3 )) {
                //企业用户注册
                    //当待注册商家为企业用户注册时
                    //上传材料的图片地址
                //法人身份证正面照
                identificationReq.setE25( storeApplyDto.getIdentityAImg() );
                //法人身份证反面照
                identificationReq.setE26( storeApplyDto.getIdentityBImg() );
                //银行开户证明
                identificationReq.setE27( storeApplyDto.getBankOpen() );
                //店面门头照
                identificationReq.setE29( storeApplyDto.getStoreFront() );
                //营业执照(三证合一)
                identificationReq.setE21( storeApplyDto.getLicenceImg() );
                //打包
                 payRes =  kftPayService.pack( "2018072300096619",MerchantTypeEnum.ENTERPRISE,identificationReq );
            } else if(storeApplyDto.getStoreType().equals( 2 )){
                //个体工商户注册
                    //当待注册商家为个体工商户时
                    //上传材料的图片地址
                //营业执照（三证合一）
                identificationReq.setI30( storeApplyDto.getLicenceImg() );
                //法人身份证正面照
                identificationReq.setI32( storeApplyDto.getIdentityAImg() );
                //法人身份证反面照
                identificationReq.setI33( storeApplyDto.getIdentityBImg() );
                //银行卡正面照
                identificationReq.setI34( storeApplyDto.getBankCardFront() );
                //银行卡反面照
                identificationReq.setI35( storeApplyDto.getBankCardBack() );
                //手持身份证正面照
                identificationReq.setI36( storeApplyDto.getIdCardHold() );
                //店面门头照
                identificationReq.setI37( storeApplyDto.getStoreFront() );
                //打包
                 payRes =  kftPayService.pack( "2018072300096619",MerchantTypeEnum.INDIVIDUAL_BUSINESS,identificationReq );
            }else if(storeApplyDto.getStoreType().equals( 1 )){
                //当待注册商家为个人商户时
                //上传材料的图片地址
                identificationReq.setP10( storeApplyDto.getIdentityAImg() );
                identificationReq.setP11( storeApplyDto.getIdentityBImg() );
                identificationReq.setP12( storeApplyDto.getIdCardHold() );
                identificationReq.setP13( storeApplyDto.getBankCardFront() );
                identificationReq.setP14( storeApplyDto.getBankCardBack() );
                identificationReq.setP15(storeApplyDto.getStoreFront());
                //打包
                 payRes =  kftPayService.pack( "2018072300096619",MerchantTypeEnum.PERSONAL,identificationReq );
            }


            Member member = memberMapper.selectByPrimaryKey( storeApplyDto.getMId() );

            if (payRes.valid()) {
                //打包成功
                Map<String, String> map = (Map) payRes.getData();
                System.out.println( map );
                PayRes payRes1 = kftPayService.sftp( map.get( "date" ), map.get( "path" ), map.get( "name" ) );
                if (payRes1.valid()) {
                    //上传成功  调用注册
                    log.info( "文件上传成功！" );
                    SecmerchantReq secmerchantReq = new SecmerchantReq();
                    secmerchantReq.setService( "amp_secmerchant_add" );
                    secmerchantReq.setVersion( baseReqConfig.getVersion() );
                    secmerchantReq.setCharset( baseReqConfig.getCharset() );
                    secmerchantReq.setLanguage( baseReqConfig.getLanguage() );
                    secmerchantReq.setCallerIp( "60.186.219.109" );
                    secmerchantReq.setMerchantId( "2018072300096619" );


                    secmerchantReq.setSecMerchantName( storeApplyDto.getMerchantName() );
                    secmerchantReq.setShortName( storeApplyDto.getMerchantName() );

                    secmerchantReq.setLegalName( member.getName() );
                    secmerchantReq.setContactName( member.getName() );
                    secmerchantReq.setContactPhone( member.getPhone() );


                    secmerchantReq.setContactEmail( "1234@qq.com" );
                    //查询出该商户对应的省市区编号和经营类目编号
                    secmerchantReq.setDistrict( kftprovincialcityMapper.selectByDistrict( storeApplyDto ).getCode() );
                    secmerchantReq.setCategory(kftBusinesscategoryMapper.selectByCategory( storeApplyDto ).getBusinessNumber() );
                    secmerchantReq.setAddress( storeApplyDto.getAddress() );
                    secmerchantReq.setBusinessScene( "线下收款" );
                    if(storeApplyDto.getStoreType().equals( 1 )){
                        //个人商户
                        secmerchantReq.setMerchantProperty("1");
                    }else if(storeApplyDto.getStoreType().equals( 3 )){
                        //企业
                        secmerchantReq.setMerchantProperty("2");
                    }else if(storeApplyDto.getStoreType().equals( 2 )){
                        //个体工商户
                        secmerchantReq.setMerchantProperty("3");
                    }
                    secmerchantReq.setCertPath( ((Map) payRes1.getData()).get( "certPath" ).toString() );
                    secmerchantReq.setCertDigest( ((Map) payRes1.getData()).get( "certDigest" ).toString() );
                    //secmerchantReq.setCertIn

                    List<CertInfo> certInofs = new ArrayList<>();
                    //身份证
                    CertInfo idCard = new CertInfo();
                    idCard.setCertType( "0" );
                    idCard.setCertNo( member.getIdentityNo() );
                    idCard.setCertValidDate( storeApplyDto.getIdValidDate() );
                    //营业执照（三证合一）
                    CertInfo licence = new CertInfo();
                    licence.setCertType( "Y" );
                    licence.setCertNo( storeApplyDto.getLicenceNo() );
                    licence.setCertValidDate( storeApplyDto.getLicenceValidDate() );
                    if(storeApplyDto.getStoreType().equals( 1 )){
                        certInofs.add( idCard );
                    }else if(storeApplyDto.getStoreType().equals( 2 ) || storeApplyDto.getStoreType().equals( 3 )){
                        certInofs.add( idCard );
                        certInofs.add( licence );
                    }

                    secmerchantReq.setCorpCertInfo( certInofs );

                    SettleBankAccount settleBankAccount = new SettleBankAccount();
                    settleBankAccount.setSettleBankNo( bankNo );
                    //settleBankAccount.setSettleBankNo("1051000");
                    settleBankAccount.setSettleBankAccountNo( banks.get( 0 ).getCardNo() );
                    settleBankAccount.setSettleName( banks.get( 0 ).getName() );
                    if (storeApplyDto.getType().contains( "企业" )) {
                        //客户银行账户类型
                        //企业账户
                        settleBankAccount.setSettleBankAcctType( "2" );
                    } else {
                        //个人账户
                        settleBankAccount.setSettleBankAcctType( "1" );
                    }
                    //客户账户借记贷记类型
                    settleBankAccount.setSettleAccountCreditOrDebit( "1" );
                    secmerchantReq.setSettleBankAccount( settleBankAccount );


                    ProductFee wxApp = new ProductFee();
                    wxApp.setProductId( "010103" );
                    wxApp.setFeeType( "3" );
                    wxApp.setFeeOfRate( "60" );
                    wxApp.setFeeOfAttach( "60" );
                    ProductFee aliApp = new ProductFee();
                    aliApp.setProductId( "010203" );
                    aliApp.setFeeType( "3" );
                    aliApp.setFeeOfRate( "60" );
                    aliApp.setFeeOfAttach( "60" );
                    ProductFee smsPay = new ProductFee();
                    smsPay.setProductId( "010501" );
                    smsPay.setFeeType( "3" );
                    smsPay.setFeeOfRate( "60" );
                    smsPay.setFeeOfAttach( "60" );
                    List<ProductFee> productFees = new ArrayList<>();
                    productFees.add( wxApp );
                    productFees.add( aliApp );
                    productFees.add( smsPay );
                    secmerchantReq.setProductFees( productFees );

                    /*
                        1ZD00TTK 主动支付-退款
                        1ZD00WXA 主动支付-微信APP支付
                        1ZD00WXG 主动支付-微信公众号/H5支付
                        1ZD00WXS 主动支付-微信扫码支付
                        1ZD00ZFF 主动支付-支付宝服务窗支付
                        1ZD00ZFS 主动支付-支付宝扫码支付
                    */


                    PayRes signUp = kftPayService.ampSecmerchantAdd( secmerchantReq );
                    log.info( "注册结果" + signUp );
                    if (signUp.valid()) {
                        log.info( "注册提交成功！" );
                        kftApply.setStatus( 4 );
                        kftApply.setKftId( ((SecmerchantRes) signUp.getData()).getSecMerchantId() );
                        kftApplyMapper.updateByPrimaryKeySelective( kftApply );
                    } else {
                        log.info( "注册失败！" );
                        kftApply.setStatus( 3 );
                        kftApply.setReason( signUp.getData().toString() );
                        kftApplyMapper.updateByPrimaryKeySelective( kftApply );
                    }
                } else {
                    log.info( "文件上传失败！下次任务再重新执行" );
                }
            } else {
                log.info( "文件打包失败！" + payRes.getMessage() );
            }
        }

}

    /**
     * 查询商户注册状态
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void querySignUp() throws Exception {
        //获取需要查询注册结果的 记录   一次任务最多同时处理100条
        List<KftApply> kftApplies=kftApplyMapper.selectNeedQueryRecord();
        log.info("需要查询注册结果的记录数："+kftApplies.size());

        KftPayConfigStorage kftPayConfigStorage = new KftPayConfigStorage();
        kftPayConfigStorage.setPackPath( kftPayCommConfig.getPackPath());
        kftPayConfigStorage.setSftpPath(kftPayCommConfig.getSftpPath());
        kftPayConfigStorage.setSftpHost(kftPayCommConfig.getSftpHost());
        kftPayConfigStorage.setSftpUsername(kftPayCommConfig.getSftpUsername());
        kftPayConfigStorage.setSftpPassword(kftPayCommConfig.getSftpPassword());
        kftPayConfigStorage.setKeyPrivate(kftPayCommConfig.getKeyPrivate());
        kftPayConfigStorage.setDevGateWay(kftPayCommConfig.getDevGateWay());
        kftPayConfigStorage.setGateWay(kftPayCommConfig.getGateWay());
        kftPayConfigStorage.init();
        KftPayService kftPayService = new KftPayService(kftPayConfigStorage);

        for(KftApply apply:kftApplies){
            Store store=storeMapper.selectByMid(apply.getmId());
            SecmerchantReq secmerchantReq=new SecmerchantReq();
            secmerchantReq.setMerchantId(kppAppPayConfiguration.getMerchantId());
            if(store.getStoreType().equals( 1 )){
                secmerchantReq.setMerchantProperty("1");
            }else if(store.getStoreType().equals( 2 )){
                secmerchantReq.setMerchantProperty("3");
            }else if(store.getStoreType().equals( 3 )){
                secmerchantReq.setMerchantProperty("2");
            }
            //secmerchantReq.setMerchantProperty(store.getType().contains("企业")?"2":"3");
            secmerchantReq.setCertNo(store.getLicenceNo());
            PayRes query=kftPayService.ampSecmerchantQuery(secmerchantReq);

            log.info("商户查询结果：" + query);
            if (query.valid()) {
                log.info("查询成功！");
                apply.setStatus(2);
                apply.setKftId(((SecmerchantRes) query.getData()).getSecMerchantId());
                kftApplyMapper.updateByPrimaryKeySelective(apply);
            } else {
               log.info("注册失败！");
               apply.setStatus(3);
               apply.setReason(query.getData().toString());
               kftApplyMapper.updateByPrimaryKeySelective(apply);
            }
        }

    }


    private String getBankId(String bankName) {
        for (BankEnum type : BankEnum.values()) {
            if (bankName.contains(type.getDesc())) {
                return type.getCode();
            }
        }
        return "";
    }

}
